package com.shxc.smarttrade.old.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.payeasenet.up.lib.pay.PayEasePay;
import com.payeasenet.up.lib.utils.NetWork;
import com.payeasenet.up.lib.utils.ViewUtils;
import com.unionpay.UPPayAssistEx;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/6/9.
 */

public class RechargeStatusActivity extends PayEasePay {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_dollar)
    TextView tvDollar;
    @BindView(R.id.tv_excharge_rate)
    TextView tvExchargeRate;
    @BindView(R.id.tv_china_yuan)
    TextView tvChinaYuan;
    private double rmbAmount;
    private double dollar;
    private double rate;
    private String orderNo;

    @Override
    public void doStartUnionPayPlugin(Activity activity, String s, String s1) {
        UPPayAssistEx.startPay(activity, null, null, s, s1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_status);
        CloseAllActivity.getScreenManager().pushActivity(this);
//        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        initView();
        initData();

    }

    private void initView() {
        tvCenter.setText("确认充值");
    }

    private void initData() {
        Intent intent = getIntent();
        rate = intent.getDoubleExtra("rate", 0);
        rmbAmount = intent.getDoubleExtra("rmbAmount", 0);
        dollar = intent.getDoubleExtra("dollar", 0);
        orderNo = intent.getStringExtra("orderNo");
        tvExchargeRate.setText(rate + "");
        tvChinaYuan.setText("¥" + rmbAmount + "");
        tvDollar.setText("$" + dollar);

    }

    @OnClick({R.id.rl_left, R.id.btn_recharge})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.btn_recharge:
                startPayMoney();
                break;
        }
    }

    /**
     * 正式支付
     */
    private void startPayMoney() {
        if (NetWork.netWorkType(getApplicationContext()) != 0) {
            String mid = "12492";
            int userId = SpUtils.getInt(RechargeStatusActivity.this, "userId", -1);
//            String v_url = "http://218.75.40.82:8071/index.html";//测试用
            String v_url = "http://mayiforex.com/index.html ";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            java.util.Date data = new java.util.Date(System.currentTimeMillis());
            String curData = formatter.format(data);
            String oid = curData + "-" + mid + "-" + orderNo;
            if (userId == -1) {
                MyApplication.showToast(this, "账号异常，请重新登录！");
                return;
            }
            String mark = userId + "";
            String md5Key = "02Fq3UYefbwJ23ZV";

            createOrder(mid, oid, "", "", "",
                    "", "", rmbAmount + "", curData, "1",
                    "", "0", v_url, "admin",
                    "00", "000000000000000", mark, md5Key);
        } else {
            ViewUtils.toast(RechargeStatusActivity.this, "请连接网络!", true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String msg = "";
            int msgTag = 0;//1、支付成功 2、支付失败 3、用户取消支付 4、支付异常
            String str = data.getExtras().getString("pay_result");
            if (str != null) {
                if (str.equalsIgnoreCase("success")) {
                    if (data.hasExtra("result_data")) {
                        String builder = data.getExtras().getString("result_data");
                        try {
                            JSONObject resultJson = new JSONObject(builder);
                            String sign = resultJson.getString("sign");
                            String dataOrg = resultJson.getString("data");
                            boolean ret = this.verify(dataOrg, sign, "00");
                            if (ret) {
                                msg = "支付成功！";
                                msgTag = 1;
                            } else {
                                Log.e("success0", builder);
                                msg = "支付失败！";
                                msgTag = 2;
                            }
                        } catch (JSONException var11) {
                        }
                    } else {
                        msg = "支付成功！";
                        msgTag = 1;
                    }
                } else if (str.equalsIgnoreCase("fail")) {
                    msg = "支付失败！";
                    msgTag = 2;
                } else if (str.equalsIgnoreCase("cancel")) {
                    msg = "用户取消了支付";
                    msgTag = 3;
                }
            } else {
                msg = "支付异常";
                msgTag = 4;
            }
            depositUpdata(orderNo, str);
            Intent intent = new Intent(this, RechargeResultActivity.class);
            intent.putExtra("rmbAmount", rmbAmount);
            intent.putExtra("rate", rate);
            intent.putExtra("dollar", dollar);
            if (msgTag == 1) {
                //跳到支付成功页面
                intent.putExtra("status", 0);
            } else {
                //跳转到支付异常界面
                intent.putExtra("status", 1);
            }
            startActivity(intent);

        }
    }

    public boolean verify(String msg, String sign64, String mode) {
        return true;
    }

    /**
     * 必须加注解，否则无效
     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(EventDatas event) {
//        if (event.getTagOne().equals(EventContents.RECHARGE_RESULT_ACTIVITY)) {
//            finish();
//        }
//    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
        CloseAllActivity.getScreenManager().popActivity(this);

    }

    /**
     * 上传入金结果
     *
     * @param orderNo
     * @param payStatus
     */
    private void depositUpdata(String orderNo, String payStatus) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("orderNo", orderNo);
        map.put("payStatus", payStatus);
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.RECHARGE_STATUS_ACTIVITY_DEPOSIT_UPDATE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                MyApplication.showToast(RechargeStatusActivity.this, "网络异常");

            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsob = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsob.get("err_code").isJsonNull())
                        errCode = jsob.get("err_code").getAsString();
                    if (!jsob.get("err_msg").isJsonNull())
                        errMsg = jsob.get("err_msg").getAsString();
                    if (!errCode.equals("0"))
                        MyApplication.showToast(RechargeStatusActivity.this, errMsg);

                }
            }
        });
    }
}
